package org.common.utils.generatortable;

import org.common.utils.generatortable.data.DataManager;
import org.common.utils.generatortable.window.GeneratorTableWindow;
import org.common.utils.tool.window.ComponentTool;
import org.common.utils.tool.window.PlaceholderTool;
import org.common.utils.tool.window.RedirectSystemPrintln;
import org.common.utils.tool.window.VersionTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author zhouzhibing
 * @date 2025/2/24
 */
public class GeneratorTableManager {
    private static final Logger log = LoggerFactory.getLogger(GeneratorTableManager.class);

    private static final GeneratorTableManager INSTANCE = new GeneratorTableManager();

    private Map<Class<?> , Map<String , Component>> componentMap;

    private GeneratorTableWindow window;

    private DataManager dataManager = new DataManager();

    private GeneratorTableManager() {

    }

    public static GeneratorTableManager getInstance() {
        return INSTANCE;
    }


    public void initBefore(GeneratorTableWindow window) {
        this.dataManager.initBefore();
    }

    public void initAfter(GeneratorTableWindow window) {
        this.componentMap = ComponentTool.getComponents(window);
        PlaceholderTool.register(getComponent(JTextField.class, "txtMysqlHost") , getString("GeneratorTableWindow.txtMysqlHost.example.text"));
        PlaceholderTool.register(getComponent(JTextField.class, "txtGeneratorDir") , getString("GeneratorTableWindow.txtGeneratorDir.example.text"));
        PlaceholderTool.register(getComponent(JTextField.class, "txtPackageName") , getString("GeneratorTableWindow.txtPackageName.example.text"));
        VersionTool.initVersionTitle(window , getString("GeneratorTableWindow.this.title"));
        RedirectSystemPrintln.redirect(getComponent(JTextArea.class, "txtAreaLog"));
    }


    public String getString(String key) {
        return ResourceBundle.getBundle("localization").getString(key);
    }

    public GeneratorTableWindow getWindow() {
        return window;
    }

    public DataManager getDataManager() {
        return dataManager;
    }

    /**
     * 根据指定类型和名称，获取组件对象
     * @param clzss 组件类型
     * @param name 组件名称
     * @return 返回对应的组件对象
     * @param <T> 接收泛型
     */
    public <T extends Component> T getComponent(Class<T> clzss , String name) {
        Map<String, Component> classMap = componentMap.get(clzss);
        if(classMap == null)
            return null;
        return (T)classMap.get(name);
    }

}
